﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Postnuclear.Test.Helpers;

namespace Postnuclear.Test
  {
  /// <summary>
  /// Represents a test class for the <see cref="WeakReference{TTarget}"/> class.
  /// </summary>
  [TestClass]
  public sealed class WeakReferenceTest
    : TestClassBase
    {
    #region Public

    // Methods

    /// <summary>
    /// A test for <see cref="WeakReference{TTarget}.Target" /> property.
    /// </summary>
    [TestMethod]
    public void TargetTest()
      {
      object target = new object();
      WeakReference<object> weakReference = new WeakReference<object>(target);
      Assert.AreEqual(target, weakReference.Target);
      }

    /// <summary>
    /// A test for to check the weak referencing of the <see cref="WeakReference{TTarget}.Target" />.
    /// </summary>
    [TestMethod]
    public void GarbageCollectionTest()
      {
      object value = new object();
      WeakReference<object> weakReference = new WeakReference<object>(value);

      Assert.IsTrue(weakReference.IsAlive);
      Assert.IsNotNull(weakReference.Target);

      value = null;
      GarbageCollector.CollectAndWaitForPendingFinalizers();

      Assert.IsFalse(weakReference.IsAlive);
      Assert.IsNull(weakReference.Target);
      }

    /// <summary>
    /// A test for to check the correctness of equality check for the weak reference.
    /// </summary>
    [TestMethod]
    public void EqualsTest()
      {
      object value = new object();
      WeakReference<object> weakReferenceA, weakReferenceB;

      weakReferenceA = value;
      weakReferenceB = weakReferenceA;
      Assert.IsTrue(weakReferenceA == weakReferenceB);

      weakReferenceB = value;
      Assert.IsTrue(weakReferenceA == weakReferenceB);

      weakReferenceB = new object();
      Assert.IsFalse(weakReferenceA == weakReferenceB);

      value = null;
      GarbageCollector.CollectAndWaitForPendingFinalizers();
      Assert.IsTrue(weakReferenceA == weakReferenceB);
      }

    #endregion
    }
  }
